<template>
  <div class="address-area">
    <van-nav-bar
      title="常用地址"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-address-list
      :disabled-list="addressList"
      @add="onAdd"
      @edit-disabled="onEdit"
      @select-disabled="handleSelect"
    />
  </div>
</template>

<script>
  import axios from 'axios';
  import RequestUrl from '../../serverApi';
  export default {
    data() {
      return {
        addressList: [],
      }
    },
    created() {
      this.getAddressList();
    },
    methods: {
      onClickLeft() {
        this.$router.go(-1);
      },
      onAdd() {
        this.$router.push({name: 'AddAddress', query: {addressId: undefined}});
      },
      onEdit(item) {
        this.$router.push({name: 'AddAddress', query: {addressId: item.id}});
      },
      handleSelect(item) {
        const { goodsId } = this.$route.query;
        if (goodsId) {
          this.$router.push({name: 'Purchase', query: {goodsId, addressId: item.id}});
        }
      },
      getAddressList() {
        axios.get(RequestUrl.getAddressList).then((res) => {
          const data = res.data;
          if (data.code === 200 && data.message) {
            const list = (data.message || []).map((item) => {
              return {
                ...item,
                tel: item.telephone,
                address: `${item.province}${item.city}${item.county}${item.addressDetail}`,
                id: item._id,
              }
            })
            this.addressList = list;
          }
        }).catch((err) => {
          console.log(err);
        });
      },
    },
  }
</script>

<style scoped>
  .van-address-list {
    padding-bottom: 0;
  }
</style>